<template>
  <view class="page">
    <view class="container">
      <!-- 顶部返回按钮 -->
      <view class="back-btn" @click="uni.navigateBack()">
        <image class="back-icon" src="@/static/icons/pageReturn.svg" mode="aspectFit"></image>
      </view>

      <!-- 标题 -->
      <view class="title">用户注册</view>

      <!-- 输入框区域 -->
      <view class="input-area">
        <input
            type="text"
            class="input-field"
            placeholder="+86 请输入手机号"
            v-model="formData.phone"
        />

        <input
            type="text"
            class="input-field"
            placeholder="请输入昵称"
            v-model="formData.nickname"
        />

        <!-- 密码输入框 -->
        <view class="password-input">
          <input
              type="text"
              class="input-field"
              placeholder="请输入密码(至少6位)"
              v-model="displayPassword"
              @input="handlePasswordInput"
          />
          <view class="eye-icon-button" @tap="togglePasswordVisibility">
            <view class="eye-icon-inner">
              <image
                  class="eye-icon"
                  :src="showPassword ? '/static/icons/eye_open.svg' : '/static/icons/eye_close.svg'"
                  mode="aspectFit"
              ></image>
            </view>
          </view>
        </view>

        <!-- 确认密码输入框 -->
        <view class="password-input">
          <input
              type="text"
              class="input-field"
              placeholder="请再次输入密码"
              v-model="displayConfirmPassword"
              @input="handleConfirmPasswordInput"
          />
          <view class="eye-icon-button" @tap="toggleConfirmPasswordVisibility">
            <view class="eye-icon-inner">
              <image
                  class="eye-icon"
                  :src="showConfirmPassword ? '/static/icons/eye_open.svg' : '/static/icons/eye_close.svg'"
                  mode="aspectFit"
              ></image>
            </view>
          </view>
        </view>

        <button
            class="submit-btn"
            :class="{ active: canSubmit }"
            :disabled="!canSubmit"
            @click="handleSubmit"
        >
          注册
        </button>
      </view>

      <!-- 切换到登录 -->
      <view class="switch-login">
        <text @click="switchToLogin">已有账号？立即登录</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import userApi from '@/http/models/user';

const showPassword = ref(false);
const showConfirmPassword = ref(false);

// 实际密码存储
const realPassword = ref('');
const realConfirmPassword = ref('');

// 显示用密码
const displayPassword = ref('');
const displayConfirmPassword = ref('');

// 表单数据
const formData = ref({
  phone: '',
  nickname: '',
  password: '',
  confirmPassword: ''
});

// 监听真实密码变化，更新显示密码
watch(realPassword, (newVal) => {
  if (showPassword.value) {
    displayPassword.value = newVal; // 显示真实密码
  } else {
    displayPassword.value = '*'.repeat(newVal.length); // 显示*号
  }
});

// 监听真实确认密码变化，更新显示密码
watch(realConfirmPassword, (newVal) => {
  if (showConfirmPassword.value) {
    displayConfirmPassword.value = newVal; // 显示真实密码
  } else {
    displayConfirmPassword.value = '*'.repeat(newVal.length); // 显示*号
  }
});

// 处理密码输入
const handlePasswordInput = () => {
  if (showPassword.value) {
    // 如果显示真实密码，用户输入的是真实密码
    realPassword.value = displayPassword.value;
  } else {
    // 如果显示*号，根据输入长度更新真实密码
    const inputLength = displayPassword.value.length;
    const currentLength = realPassword.value.length;

    if (inputLength > currentLength) {
      // 用户输入了新字符
      realPassword.value += displayPassword.value.slice(-1);
    } else if (inputLength < currentLength) {
      // 用户删除了字符
      realPassword.value = realPassword.value.slice(0, -1);
    }
  }
  formData.value.password = realPassword.value;
};

// 处理确认密码输入
const handleConfirmPasswordInput = () => {
  if (showConfirmPassword.value) {
    realConfirmPassword.value = displayConfirmPassword.value;
  } else {
    const inputLength = displayConfirmPassword.value.length;
    const currentLength = realConfirmPassword.value.length;

    if (inputLength > currentLength) {
      realConfirmPassword.value += displayConfirmPassword.value.slice(-1);
    } else if (inputLength < currentLength) {
      realConfirmPassword.value = realConfirmPassword.value.slice(0, -1);
    }
  }
  formData.value.confirmPassword = realConfirmPassword.value;
};

// 切换密码可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;

  if (showPassword.value) {
    // 显示真实密码
    displayPassword.value = realPassword.value;
  } else {
    // 显示*号
    displayPassword.value = '*'.repeat(realPassword.value.length);
  }
};

// 切换确认密码可见性
const toggleConfirmPasswordVisibility = () => {
  showConfirmPassword.value = !showConfirmPassword.value;

  if (showConfirmPassword.value) {
    displayConfirmPassword.value = realConfirmPassword.value;
  } else {
    displayConfirmPassword.value = '*'.repeat(realConfirmPassword.value.length);
  }
};

// 计算属性：手机号是否有效
const isPhoneValid = computed(() => {
  return /^1[3-9]\d{9}$/.test(formData.value.phone);
});

// 计算属性：是否可以提交表单
const canSubmit = computed(() => {
  return (
      isPhoneValid.value &&
      formData.value.nickname.trim() !== '' &&
      realPassword.value.length >= 6 &&
      realPassword.value === realConfirmPassword.value
  );
});

// 切换到登录模式
const switchToLogin = () => {
  uni.redirectTo({
    url: '/pages/login/login'
  });
};

// 处理提交
const handleSubmit = async () => {
  if (!canSubmit.value) return;

  try {
    const res = await userApi.register({
      phone: formData.value.phone,
      password: realPassword.value,
      nickname: formData.value.nickname,
      uid: generateUID()
    });

    if (res.code === 200) {
      await uni.showToast({title: '注册成功', icon: 'success'});
      setTimeout(() => {
        uni.redirectTo({url: '/pages/login/login'});
      }, 1500);
    } else {
      await uni.showToast({title: res.msg || '注册失败', icon: 'none'});
    }
  } catch (error) {
    console.error('注册失败:', error);
    uni.showToast({ title: '注册失败，请稍后重试', icon: 'none' });
  }
};

// 生成唯一标识
const generateUID = () => {
  return 'uid_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
};
</script>

<style scoped>
@import '../../components/scss/login-common.css';

.switch-login {
  text-align: center;
  margin-top: 25px;
  font-size: 15px;
  color: white;
  cursor: pointer;
  text-decoration: underline;
}
</style>